//
//  FirCirNewsDataSource.m
//  tcpoctest
//
//  Created by apple on 13-4-25.
//  Copyright (c) 2013年 gump. All rights reserved.
//

#import "FirCirNewsDataSource.h"
#import "FriendStatus.h"

#import "FirCirNewsMailDataSource.h"
#import "FirCirLocalResourceDataSource.h"
#import "sendFirCirGetNews.h"

@implementation FirCirNewsDataSource
-(id)init
{
    self = [super init];
    if (self != nil) {
        pthread_mutex_init(&mutexnew, 0);
        newsDic = [[NSMutableDictionary alloc] init];
        searcharr = [[NSMutableArray alloc] init];
    }
    
    return self;
}

-(void)AddNews:(FriendStatus *)fs
{
    if (fs == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexnew);

    FriendStatus *newfs = [newsDic objectForKey:fs.statusId];
    if (newfs != nil) {
        newfs = fs;
    }
    else
    {
        [newsDic setObject:fs forKey:fs.statusId];
    }
    
    pthread_mutex_unlock(&mutexnew);
}

-(void)DelNewsByID:(NSString *)strid
{
    pthread_mutex_lock(&mutexnew);
    
    FriendStatus *fs = [newsDic objectForKey:strid];
    if (fs != nil) {
        for (NSString *picid in fs.imageIDArray) {
            [[DataControl shareControl].fcLocalRecDS DelLocalByID:picid];
        }
        
        for (NSString *commentid in fs.commentArr) {
            [[DataControl shareControl].fcLocalRecDS DelLocalByID:commentid];
        }
    }
    
    [newsDic removeObjectForKey:strid];
    
    
    pthread_mutex_unlock(&mutexnew);
}

-(void)DelAllNews
{
    pthread_mutex_lock(&mutexnew);
    
    [newsDic removeAllObjects];
    
    pthread_mutex_unlock(&mutexnew);
}

-(FriendStatus *)getNewsByID:(NSString *)strid
{
    FriendStatus *fs = nil;
    
    pthread_mutex_lock(&mutexnew);
    
    fs = [newsDic objectForKey:strid];
    if (fs == nil) {
        NSString *mail = [[DataControl shareControl].fcnewsmailDS GetMailByNewsID:strid];
        if (mail != nil &&
            ![mail isEqualToString:@""] &&
            ![strid isEqualToString:@""]) {
            if (![searcharr containsObject:strid]) {
                
                [searcharr addObject:strid];
                
                [[netManager sharedNetManager].sendFCGetNews SendFCGetNewByMail:mail withID:strid];
            }
            
        }
    }
    
    pthread_mutex_unlock(&mutexnew);
    
    return fs;
}

-(NSArray *)getAllNewsKeys
{
    NSArray *arr = nil;
    
    pthread_mutex_lock(&mutexnew);
    
    arr = [newsDic allKeys];
    
    pthread_mutex_unlock(&mutexnew);
    
    return arr;
}

-(void)RemoveSearchObjectbyID:(NSString *)strid
{
    pthread_mutex_lock(&mutexnew);
    
    [searcharr removeObject:strid];
    
    pthread_mutex_unlock(&mutexnew);
}

@end
